package com.tiyo.system.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tiyo.common.core.domain.AjaxResult;
import com.tiyo.common.core.text.Convert;
import com.tiyo.common.utils.CookieUtils;
import com.tiyo.common.utils.ServletUtils;
import com.tiyo.common.utils.StringUtils;
import com.tiyo.framework.config.SysConfig;
import com.tiyo.framework.shiro.constant.ShiroConstants;
import com.tiyo.framework.shiro.service.SysPasswordService;
import com.tiyo.framework.web.controller.BaseController;
import com.tiyo.system.mapper.domain.SysMenu;
import com.tiyo.system.mapper.domain.SysUser;
import com.tiyo.system.service.SysConfigService;
import com.tiyo.system.service.SysMenuService;

/**
 * 
 * @Description 首页操作
 * @author yangb
 * @version v1.0
 * @date 2021年1月21日
*
 */
@Controller
public class IndexController extends BaseController{
	// 系统首页
	@GetMapping("/main")
	public String main(ModelMap mmap)
	{
		return "main";
	}
	 @Autowired
    private SysMenuService menuService;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    SysPasswordService sysPasswordService;

    @Autowired
    private SysConfig sysConfig;

    // 系统首页
    @GetMapping("/index")
    public String index(ModelMap mmap)
    {
        // 取身份信息
        SysUser user = getSysUser();
        // 根据用户id取出菜单
        List<SysMenu> menus = menuService.selectMenusByUser(user);
        mmap.put("menus", menus);
        mmap.put("user", user);
        mmap.put("sideTheme", sysConfigService.selectConfigByKey("sys.index.sideTheme"));
        mmap.put("skinName", sysConfigService.selectConfigByKey("sys.index.skinName"));
        mmap.put("ignoreFooter", sysConfigService.selectConfigByKey("sys.index.ignoreFooter"));
        mmap.put("sysName", sysConfig.getName());
        mmap.put("copyrightYear", sysConfig.getCopyrightYear());
        mmap.put("sideTheme", sysConfigService.selectConfigByKey("sys.index.sideTheme"));
        mmap.put("skinName", sysConfigService.selectConfigByKey("sys.index.skinName"));
        Boolean footer = Convert.toBool(sysConfigService.selectConfigByKey("sys.index.footer"), true);
        Boolean tagsView = Convert.toBool(sysConfigService.selectConfigByKey("sys.index.tagsView"), true);
        mmap.put("footer", footer);
        mmap.put("tagsView", tagsView);
        mmap.put("mainClass", contentMainClass(footer, tagsView));
//        mmap.put("isDefaultModifyPwd", initPasswordIsModify(user.getPwdUpdateDate()));
//        mmap.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));
        mmap.put("isMobile", ServletUtils.checkAgentIsMobile(ServletUtils.getRequest().getHeader("User-Agent")));

        // 菜单导航显示风格
        String menuStyle = sysConfigService.selectConfigByKey("sys.index.menuStyle");
        // 移动端，默认使左侧导航菜单，否则取默认配置
        String indexStyle = ServletUtils.checkAgentIsMobile(ServletUtils.getRequest().getHeader("User-Agent")) ? "index" : menuStyle;
        
        // 优先Cookie配置导航菜单
        Cookie[] cookies = ServletUtils.getRequest().getCookies();
        for (Cookie cookie : cookies)
        {
            if (StringUtils.isNotEmpty(cookie.getName()) && "nav-style".equalsIgnoreCase(cookie.getName()))
            {
                indexStyle = cookie.getValue();
                break;
            }
        }
        
        String webIndex = "topnav".equalsIgnoreCase(indexStyle) ? "index-topnav" : "index";
        return webIndex;
    }
    @PostMapping("/menu")
    @ResponseBody
    public AjaxResult menu(ModelMap mmap)
    {
        return AjaxResult.success(menuService.selectMenusByUser(getSysUser()));
    }
    // 锁定屏幕
    @GetMapping("/lockscreen")
    public String lockscreen(ModelMap mmap)
    {
        mmap.put("user", getSysUser());
        ServletUtils.getSession().setAttribute(ShiroConstants.LOCK_SCREEN, true);
        return "lock";
    }
    public String contentMainClass(Boolean footer, Boolean tagsView)
    {
        if (!footer && !tagsView)
        {
            return "tagsview-footer-hide";
        }
        else if (!footer)
        {
            return "footer-hide";
        }
        else if (!tagsView)
        {
            return "tagsview-hide";
        }
        return StringUtils.EMPTY;
    }
    // 解锁屏幕
    @PostMapping("/unlockscreen")
    @ResponseBody
    public AjaxResult unlockscreen(String password)
    {
        SysUser user = getSysUser();
        if (StringUtils.isNull(user))
        {
            return AjaxResult.error("服务器超时，请重新登陆");
        }
        if (sysPasswordService.matches(user, password))
        {
            ServletUtils.getSession().removeAttribute(ShiroConstants.LOCK_SCREEN);
            return AjaxResult.success();
        }
        return AjaxResult.error("密码不正确，请重新输入。");
    }

    // 切换主题
    @GetMapping("/system/switchSkin")
    public String switchSkin()
    {
        return "skin";
    }

    // 切换菜单
    @GetMapping("/system/menuStyle/{style}")
    public void menuStyle(@PathVariable String style,ModelMap mmap, HttpServletResponse response)
    {
    	mmap.put("sysName", sysConfig.getName());
        CookieUtils.setCookie(response, "nav-style", style);
    }

    // 系统介绍
    @GetMapping("/system/main")
    public String sysMain(ModelMap mmap)
    {
//        mmap.put("version", ruoYiConfig.getVersion());
        return "main";
    }
    
    // 检查初始密码是否提醒修改
    public boolean initPasswordIsModify(Date pwdUpdateDate)
    {
//        Integer initPasswordModify = Convert.toInt(configService.selectConfigByKey("sys.account.initPasswordModify"));
//        return initPasswordModify !=null && initPasswordModify == 1 && pwdUpdateDate == null;
        return  false;
    }
    
    // 检查密码是否过期
    public boolean passwordIsExpiration(Date pwdUpdateDate)
    {
//        Integer passwordValidateDays = Convert.toInt(configService.selectConfigByKey("sys.account.passwordValidateDays"));
//        if (passwordValidateDays !=null && passwordValidateDays > 0)
//        {
//            if (StringUtils.isNull(pwdUpdateDate))
//            {
//                // 如果从未修改过初始密码，直接提醒过期
//                return true;
//            }
//            Date nowDate = DateUtils.getNowDate();
//            return DateUtils.differentDaysByMillisecond(nowDate, pwdUpdateDate) > passwordValidateDays;
//        }
        return false;
    }
}
